package net.freebytes.config.refresh.util;


import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.core.io.ClassPathResource;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 默认的配置文件目录，目前仅支持两个，如果需要，可以自行添加
 *
 * @author : 千里明月
 **/
public class ConfigUtils {

    private static final String CONFIG_FILE = "application.properties";
    private static final String DEV_CONFIG_FILE = "src/main/resources/application.properties";

    public static String getPath() {
        //优先寻找生产环境下的配置文件
        String userDir = System.getProperty("user.dir");
        File file = new File(userDir, CONFIG_FILE);
        if (file.exists()) {
            return file.getAbsolutePath();
        }
        //如果找不到，就寻找开发环境下的配置文件
        file = new File(userDir, DEV_CONFIG_FILE);
        if (file.exists()) {
            return file.getAbsolutePath();
        }

        //如果还是找不到，则去jar包中，将配置文件复制出来
        file = new File(userDir, CONFIG_FILE);
        ClassPathResource resource = new ClassPathResource(CONFIG_FILE);
        try (
                FileOutputStream out = new FileOutputStream(file);
                InputStream input = resource.getInputStream();
        ) {
            IOUtils.copy(input, out);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file.getAbsolutePath();

    }

}
